package com.bm.specialvehiclefordispatcher.activity.mywallet;

import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.SparseArray;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.bm.corelibs.logic.BaseLogic.NListener;
import com.bm.corelibs.utils.ToastMgr;
import com.bm.corelibs.utils.ViewHolder;
import com.bm.specialvehiclefordispatcher.R;
import com.bm.specialvehiclefordispatcher.activity.BaseActivity;
import com.bm.specialvehiclefordispatcher.bean.BalanceDetail;
import com.bm.specialvehiclefordispatcher.bean.BaseData;
import com.bm.specialvehiclefordispatcher.constants.Constant;
import com.bm.specialvehiclefordispatcher.logics.LoginManager;
import com.bm.specialvehiclefordispatcher.logics.WalletManager;
import com.bm.specialvehiclefordispatcher.views.CommonNavigationBar;

public class MyWalletActivity extends BaseActivity implements OnClickListener, OnScrollListener {
	CommonNavigationBar bar;
	TextView mywallet_cancarry;
	Button mywallet_recharge;
	TextView mywallet_ice, tv_empty;

	WalletManager manager = new WalletManager();
	String uid;
	double accountBalance, frozenBalance;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mywallet);
		findViews();
		init();
		addListeners();
	}

	@Override
	public void findViews() {
		bar = (CommonNavigationBar) findViewById(R.id.navi);
		mywallet_cancarry = (TextView) findViewById(R.id.mywallet_cancarry);
		mywallet_recharge = (Button) findViewById(R.id.mywallet_recharge);
		mywallet_ice = (TextView) findViewById(R.id.mywallet_ice);
		expandableListView = (ExpandableListView) findViewById(R.id.myincome_expandablelist);
		myincome_layout = (RelativeLayout) findViewById(R.id.myincome_layout);
		myincome_textview = (TextView) findViewById(R.id.myincome_textview);
		tv_empty = (TextView) findViewById(R.id.tv_empty);
	}

	@Override
	public void init() {
		uid = LoginManager.getInstance(mActivity).getUid();
		bar.setListener(null);
		bar.setTitle("我的钱包");
		loadingDialog.show();
		manager.getData(LoginManager.getInstance(mActivity).getId(), listener());
		//manager.getData("1", listener());
	}

	@Override
	public void addListeners() {
		mywallet_recharge.setOnClickListener(this);
		expandableListView.setOnScrollListener(this);
		myincome_layout.setOnClickListener(headerListener);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.mywallet_recharge:
			startActivityForResult(new Intent(mActivity, RechargeMoneyActivity.class), 1);
			break;

		default:
			break;
		}
	}

	private void setupData() {
		for (int i = 0; i < balanceDetails.size(); i++) {
			balanceDetails.get(i).month = balanceDetails.get(i).operateDate.substring(5, 7) + "月";
		}
	}

	private NListener<BaseData> listener() {
		return new NListener<BaseData>() {
			@Override
			public void onResponse(BaseData data) {
				loadingDialog.dismiss();
				if (data.status == Constant.STATUS_OK) {
					accountBalance = data.data.accountBalance;
					frozenBalance = data.data.frozenBalance;
					if (data.data.walletLogs != null && data.data.walletLogs.size() > 0) {
						balanceDetails = data.data.walletLogs;
						setupData();
						incomeAdapter = new BalanceAdapter();
						incomeAdapter.setupShowStatus();
						expandableListView.setGroupIndicator(null);
						expandableListView.setAdapter(incomeAdapter);
						fillIndexer();
						tv_empty.setVisibility(View.GONE);
					} else {
						tv_empty.setVisibility(View.VISIBLE);
					}
					setData();

				} else {
					ToastMgr.show(data.msg);
				}
			}

			@Override
			public void onErrResponse(VolleyError error) {
				loadingDialog.dismiss();
			}

			@Override
			public void onAllPageLoaded(int nowPage, int totalPage) {
			}
		};
	}

	public void setData() {
		mywallet_cancarry.setText("¥" + accountBalance);
		mywallet_ice.setText("¥" + frozenBalance);
		// balanceDetails = new ArrayList<BalanceDetail>();
		// for (int i = 1; i < 13; i++) {
		// for (int j = 0; j < 3; j++) {
		// BalanceDetail detail = new BalanceDetail();
		// detail.month = i + "月";
		// detail.money = "999";
		// detail.operateDate = "08-15 11:33";
		//
		// switch (j) {
		// case 0:
		// detail.title = "账号提现";
		// detail.subTitle = "";
		// detail.type = 1;
		// break;
		//
		// case 1:
		// detail.title = "服务被签收";
		// detail.subTitle = "订单号10086";
		// detail.type = 0;
		// List<BalanceDetail> suBalanceDetails = new ArrayList<BalanceDetail>();
		// for (int k = 0; k < 4; k++) {
		// BalanceDetail subdetail = new BalanceDetail();
		// subdetail.month = i + "月";
		// subdetail.money = "99";
		// subdetail.operateDate = "08-15 11:33";
		// subdetail.title = "运输50方";
		// subdetail.subTitle = "";
		// subdetail.type = 0;
		// suBalanceDetails.add(subdetail);
		// }
		// detail.serviceLogs = suBalanceDetails;
		// break;
		//
		// case 2:
		// detail.title = "取消订单赔偿";
		// detail.subTitle = "";
		// detail.type = 0;
		// break;
		// }
		//
		// balanceDetails.add(detail);
		// }
		// }
	}

	private OnClickListener headerListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			String month = myincome_textview.getText().toString().trim();
			for (int i = 0; i < incomeAdapter.getGroupCount(); i++) {
				if (month.equals(showStatus.get(i).month)) {
					showStatus.get(i).shouldShow = !showStatus.get(i).shouldShow;
				}
			}
			fillIndexer();
			incomeAdapter.notifyDataSetChanged();
		}
	};

	private SparseArray<String> indexer = new SparseArray<String>();

	private void fillIndexer() {
		indexer.clear();
		for (int i = 0; i < incomeAdapter.getGroupCount(); i++) {
			indexer.put(indexer.size(), showStatus.get(i).shouldShow ? balanceDetails.get(i).month : "");
			if (childExpandStatus.get(i)) {
				for (int j = 0; j < incomeAdapter.getChildrenCount(i); j++) {
					indexer.put(indexer.size(), balanceDetails.get(i).month);
				}
			}
		}
	}

	private SparseArray<ShowEntity> showStatus = new SparseArray<ShowEntity>();
	private SparseBooleanArray childExpandStatus = new SparseBooleanArray();

	ExpandableListView expandableListView;
	BalanceAdapter incomeAdapter;
	List<BalanceDetail> balanceDetails;
	RelativeLayout myincome_layout;
	TextView myincome_textview;

	class BalanceAdapter extends BaseExpandableListAdapter implements OnClickListener {

		private String current = "", prevous = "";

		public void setupShowStatus() {
			if (balanceDetails == null)
				return;

			for (int i = 0; i < getGroupCount(); i++) {
				ShowEntity entity = new ShowEntity();
				entity.month = balanceDetails.get(i).month;
				entity.shouldShow = true;
				showStatus.put(i, entity);
			}
		}

		@Override
		public int getGroupCount() {
			return balanceDetails == null ? 0 : balanceDetails.size();
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			return balanceDetails.get(groupPosition).serviceLogs == null ? 0 : balanceDetails.get(groupPosition).serviceLogs.size();
		}

		@Override
		public Object getGroup(int groupPosition) {
			return balanceDetails.get(groupPosition);
		}

		@Override
		public Object getChild(int groupPosition, int childPosition) {
			return balanceDetails.get(groupPosition).serviceLogs.get(childPosition);
		}

		@Override
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		@Override
		public boolean hasStableIds() {
			return false;
		}

		@Override
		public void onGroupCollapsed(int groupPosition) {
			childExpandStatus.put(groupPosition, false);
			fillIndexer();
		}

		@Override
		public void onGroupExpanded(int groupPosition) {
			childExpandStatus.put(groupPosition, true);
			fillIndexer();
		}

		@SuppressLint("InflateParams")
		@Override
		public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
			if (convertView == null)
				convertView = LayoutInflater.from(mActivity).inflate(R.layout.item_groupview1, null);

			BalanceDetail detail = balanceDetails.get(groupPosition);
			ShowEntity showEntity = showStatus.get(groupPosition);

			RelativeLayout rl_month = ViewHolder.get(convertView, R.id.rl_month);
			RelativeLayout content = ViewHolder.get(convertView, R.id.content);
			TextView month = ViewHolder.get(convertView, R.id.month);
			ImageView iv_month = ViewHolder.get(convertView, R.id.iv_month);
			View f_divider = ViewHolder.get(convertView, R.id.f_divider);
			TextView title = ViewHolder.get(convertView, R.id.title);
			TextView subtitle = ViewHolder.get(convertView, R.id.subtitle);
			TextView price = ViewHolder.get(convertView, R.id.price);
			TextView time = ViewHolder.get(convertView, R.id.time);
			View s_divider = ViewHolder.get(convertView, R.id.s_divider);

			if (showEntity.shouldShow) {
				content.setVisibility(View.VISIBLE);
				f_divider.setVisibility(View.VISIBLE);
				s_divider.setVisibility(View.VISIBLE);
				iv_month.setImageResource(R.drawable.up_arrow);
				title.setText(detail.title);
				List<BalanceDetail> childs = detail.serviceLogs;
				double money = 0;
				if(childs == null || childs.size() <= 0)
					price.setText(detail.pay.equals(uid) ? "-" + detail.money : "+" + detail.money);
				else {
					for (int i = 0; i < childs.size(); i++) {
						money += Double.valueOf(childs.get(i).realsumPrice);
					}
					price.setText(detail.pay.equals(uid) ? "-" + money : "+" + money);
				}
				time.setText(detail.operateDate);
				subtitle.setText(detail.subTitle);
			} else {
				content.setVisibility(View.GONE);
				s_divider.setVisibility(View.GONE);
				f_divider.setVisibility(View.GONE);
				iv_month.setImageResource(R.drawable.down_arrow);
			}

			// if (groupPosition < getGroupCount() - 1) {
			// next = detail.month;
			// }

			if (groupPosition == 0) {
				month.setText(detail.month);
				rl_month.setVisibility(View.VISIBLE);
				rl_month.setTag(detail.month);
				rl_month.setOnClickListener(this);
				f_divider.setVisibility(View.VISIBLE);
			} else {
				current = detail.month;
				prevous = balanceDetails.get(groupPosition - 1).month;
				if (!current.equals(prevous)) {
					month.setText(current);
					rl_month.setVisibility(View.VISIBLE);
					rl_month.setTag(detail.month);
					rl_month.setOnClickListener(this);
					f_divider.setVisibility(View.VISIBLE);
				} else {
					rl_month.setVisibility(View.GONE);
					f_divider.setVisibility(View.GONE);
				}
			}
			return convertView;
		}

		@SuppressLint("InflateParams")
		@Override
		public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
			if (convertView == null)
				convertView = LayoutInflater.from(mActivity).inflate(R.layout.item_childview1, null);

			BalanceDetail detail = balanceDetails.get(groupPosition).serviceLogs.get(childPosition);
			ShowEntity showEntity = showStatus.get(groupPosition);

			RelativeLayout c_content = ViewHolder.get(convertView, R.id.c_content);
			TextView c_title = ViewHolder.get(convertView, R.id.c_title);
			TextView c_price = ViewHolder.get(convertView, R.id.c_price);
			TextView c_time = ViewHolder.get(convertView, R.id.c_time);
			View c_divider = ViewHolder.get(convertView, R.id.c_divider);

			if (showEntity.shouldShow) {
				c_content.setVisibility(View.VISIBLE);
				c_title.setText("方量" + detail.volume + "方");
				c_price.setText(balanceDetails.get(groupPosition).pay.equals(uid) ? "-" + detail.realsumPrice : "+" + detail.realsumPrice);
				c_time.setText(detail.startTime);

				if (childPosition == getChildrenCount(groupPosition) - 1)
					c_divider.setVisibility(View.GONE);
				else
					c_divider.setVisibility(View.VISIBLE);
			} else {
				c_content.setVisibility(View.GONE);
			}

			return convertView;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return false;
		}

		@Override
		public void onClick(View v) {
			String month = (String) v.getTag();
			for (int i = 0; i < getGroupCount(); i++) {
				if (month.equals(showStatus.get(i).month)) {
					showStatus.get(i).shouldShow = !showStatus.get(i).shouldShow;
				}
			}
			fillIndexer();
			incomeAdapter.notifyDataSetChanged();
		}

	}

	class ShowEntity {
		public String month;
		public boolean shouldShow = true;
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		if (firstVisibleItem == 0)
			myincome_layout.setVisibility(View.GONE);
		else {
			myincome_layout.setVisibility(View.VISIBLE);
			if (indexer.get(firstVisibleItem).length() <= 0)
				myincome_layout.setVisibility(View.GONE);
			else {
				myincome_layout.setVisibility(View.VISIBLE);
				myincome_textview.setText(indexer.get(firstVisibleItem));
			}
		}
	}
	
	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		if(arg1 == RESULT_OK) {
			loadingDialog.show();
			manager.getData(LoginManager.getInstance(mActivity).getId(), listener());
		}
	}

}
